<template>
  <view class="shop-container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-input">
        <image class="search-icon" src="/static/icons/search.png"></image>
        <input
          type="text"
          placeholder="搜索禅意好物"
          placeholder-class="search-placeholder"
          @click="handleSearch()"
        />
      </view>
    </view>

    <!-- 分类导航 -->
    <scroll-view class="category-nav" scroll-x="true" show-scrollbar="false">
      <view
        class="category-item"
        :class="{ active: class_id === 0 }"
        @tap="switchCategory(0)"
      >
        <view class="category-icon-wrapper">
          <i class="category-icon iconfont icon-31quanbushangpin"></i>
        </view>
        <text class="category-name">全部</text>
      </view>
      <view
        v-for="(item, index) in categories"
        :key="index"
        class="category-item"
        :class="{ active: class_id === item.category_id }"
        @tap="switchCategory(item.category_id)"
      >
        <view class="category-icon-wrapper">
          <image :src="item.images.file_path" class="category-icon"></image>
        </view>
        <text class="category-name">{{ item.name }}</text>
      </view>
    </scroll-view>

    <!-- 二级分类 -->
    <!-- <view class="subcategory-wrapper" v-if="showSubCategories && currentCategory && currentCategory.subCategories">
      <scroll-view class="subcategory-nav" scroll-x="true" show-scrollbar="false">
        <view 
          v-for="(subCat, index) in currentCategory.subCategories" 
          :key="index" 
          class="subcategory-item" 
          :class="{ active: currentSubCat === index }"
          @tap="switchSubCategory(index)"
        >
          <text class="subcategory-name">{{subCat.name}}</text>
        </view>
      </scroll-view>
    </view> -->

    <!-- 主推荐位 -->
    <!-- <view class="featured-section">
      <view class="section-title">
        <text class="title-text">本月推荐</text>
        <view class="title-decor"></view>
      </view>
      <scroll-view class="featured-scroll" scroll-x="true" show-scrollbar="false">
        <view 
          v-for="(item, index) in featuredProducts" 
          :key="index" 
          class="featured-item"
          @tap="navigateToDetail(item.id)"
        >
          <image class="featured-image" :src="item.image" mode="aspectFill"></image>
          <view class="featured-info">
            <text class="featured-name">{{item.name}}</text>
            <text class="featured-price">¥{{item.price}}</text>
          </view>
        </view>
      </scroll-view>
    </view> -->

    <!-- 商品列表 -->
    <view class="product-section">
      <view class="section-title">
        <text class="title-text">禅意好物</text>
        <view class="title-decor"></view>
      </view>
      <view class="filter-bar">
        <view
          v-for="(item, index) in filterOptions"
          :key="index"
          class="filter-item"
          :class="{ active: currentFilter === index }"
          @tap="setFilter(index)"
        >
          <text>{{ item.name }}</text>
          <view class="filter-indicator"></view>
        </view>
      </view>
      <view class="product-grid">
        <view
          v-for="(item, index) in productList"
          :key="index"
          class="product-item"
          @tap="navigateToDetail(item.product_id)"
        >
          <image
            class="product-image"
            :src="item.product_image"
            mode="aspectFill"
          ></image>
          <!-- <view class="product-tag" v-if="item.tag">{{item.tag}}</view> -->
          <view class="product-info">
            <text class="product-name">{{ item.product_name }}</text>
            <text class="product-desc">{{ item.selling_point }}</text>
            <view class="product-price-row">
              <text class="product-price">¥{{ item.product_price }}</text>
              <text class="product-sold">{{ item.product_sales }}人已选</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view class="load-more" @tap="loadCategoryProducts">
      <view class="load-text" v-if="!isLoading">
        {{ hasMore ? "点击加载更多" : "我已经到底了" }}
      </view>
      <view class="loading-indicator" v-else>
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
    </view>

    <!-- 底部区域 -->
    <view class="bottom-space"></view>

    <!-- 底部工具栏 -->
    <!-- <view class="bottom-toolbar">
      <view class="toolbar-item" @tap="navigateToHome">
        <image class="toolbar-icon" src="/static/icons/home.png"></image>
        <text class="toolbar-text">首页</text>
      </view>
      <view class="toolbar-item" @tap="navigateToShop">
        <image class="toolbar-icon" src="/static/icons/shop.png"></image>
        <text class="toolbar-text">商城</text>
      </view>
      <view class="toolbar-item" @tap="openCart">
        <view class="toolbar-icon-wrapper">
          <image class="toolbar-icon" src="/static/icons/cart.png"></image>
          <view class="toolbar-badge" v-if="cartCount > 0">{{cartCount}}</view>
        </view>
        <text class="toolbar-text">购物车</text>
      </view>
      <view class="toolbar-item" @tap="navigateToMine">
        <image class="toolbar-icon" src="/static/icons/user.png"></image>
        <text class="toolbar-text">我的</text>
      </view>
    </view> -->

    <!-- 积分抵扣提示 -->
    <!-- <view class="points-tip" v-if="userPoints > 0">
      <image class="points-icon" src="/static/icons/points.png"></image>
      <text class="points-text">您有{{userPoints}}积分可用于抵扣，最高可抵￥{{calculateMaxDiscount()}}</text>
      <view class="points-detail" @tap="showPointsRules">详情</view>
    </view> -->

    <!-- 积分规则弹窗 -->
    <!-- <view class="points-modal" v-if="showPointsModal">
      <view class="points-modal-content">
        <view class="points-modal-header">
          <text class="points-modal-title">积分抵扣规则</text>
          <view class="points-modal-close" @tap="hidePointsRules">×</view>
        </view>
        <view class="points-modal-body">
          <view class="points-rule-item">
            <text class="points-rule-title">阶梯式抵扣规则</text>
            <view class="points-rule-desc">
              <text>• 积分达到500可抵扣商品金额的5%</text>
              <text>• 积分达到1000可抵扣商品金额的8%</text>
              <text>• 积分达到2000可抵扣商品金额的12%</text>
              <text>• 积分达到5000可抵扣商品金额的15%</text>
            </view>
          </view>
          <view class="points-rule-item">
            <text class="points-rule-title">使用说明</text>
            <view class="points-rule-desc">
              <text>• 每100积分等值1元人民币</text>
              <text>• 单笔订单最高可抵扣订单金额的50%</text>
              <text>• 部分特价商品不参与积分抵扣</text>
            </view>
          </view>
        </view>
        <view class="points-modal-footer">
          <button class="points-modal-btn" @tap="hidePointsRules">我知道了</button>
        </view>
      </view>
    </view> -->

    <!-- 悬浮购物车 -->
    <view class="float-cart" @tap="openCart">
      <image class="cart-icon" src="/static/cart.png"></image>
      <view class="cart-badge" v-if="cartCount > 0">{{ cartCount }}</view>
    </view>
  </view>
</template>

<script>
import { getCartNumApi } from "../../api/order";
import { productCategoryApi, productListApi } from "../../api/product";
export default {
  data() {
    return {
      class_id: 0,
      currentSubCat: 0,
      currentFilter: 0,
      isLoading: false,
      cartCount: 0,
      showSubCategories: false,
      currentCategory: null,
      userPoints: 0,
      showPointsModal: false,
      categories: [],
      filterOptions: [
        {
          type: "all",
          name: "综合",
        },
        {
          type: "sales",
          name: "销量",
        },
        {
          type: "price",
          name: "价格",
        },
      ],
      featuredProducts: [],
      page: 0,
      hasMore: true,
    };
  },
  onLoad() {
    productCategoryApi().then((res) => {
      this.categories = res.list;
    });
    getCartNumApi().then((res) => {
      this.cartCount = res.cartNum || 0;
    });
  },
  onShow() {
    let localClass = uni.getStorageSync("shop_class");
    uni.setStorageSync("shop_class", 0);
    if (localClass > 0) {
      if (localClass != this.class_id) {
        this.class_id = localClass;
      }
    }
    console.log(this.class_id);
  },
  watch: {
    class_id: {
      handler(newValue, oldValue) {
        if (newValue != oldValue) {
          this.init();
        }
      },
      immediate: true,
    },
  },
  methods: {
    handleSearch() {
      // 定义路由映射表
      const routeMap = {
        path: "/pages/shapping/seacher",
        animationType: "slide-in-right",
      };
      // 执行跳转
      uni.navigateTo({
        url: routeMap.path,
        animationType: routeMap.animationType,
        success: () => {
          // 跳转成功后的跟踪逻辑
          this.$trackEvent("nav_click", {
            type: "search",
          });
        },
        fail: (err) => {
          console.error("跳转失败:", err);
        },
      });
    },
    switchCategory(class_id) {
      this.class_id = class_id;
      if (class_id > 0) {
        this.currentCategory = this.categories.find(
          (item) => item.category_id == class_id
        );
        // 检查是否有二级分类
        if (
          this.currentCategory &&
          this.currentCategory.subCategories &&
          this.currentCategory.subCategories.length > 0
        ) {
          this.showSubCategories = true;
          this.currentSubCat = 0;
        } else {
          this.showSubCategories = false;
        }
        // 加载一级分类的商品
        this.init();
      }
    },

    switchSubCategory(index) {
      this.currentSubCat = index;

      // 加载二级分类的商品
      const subCategoryId = this.currentCategory.subCategories[index].id;
      this.loadSubCategoryProducts(subCategoryId);

      uni.showToast({
        title: `已切换到${this.currentCategory.subCategories[index].name}`,
        icon: "none",
      });
    },
    init() {
      this.page = 0;
      this.hasMore = true;
      this.productList = [];
      this.loadCategoryProducts();
    },
    loadCategoryProducts() {
      if (!this.hasMore || this.isLoading) {
        return;
      }
      this.isLoading = true;
      this.page++;
      productListApi({
        category_id: this.class_id,
        list_rows: 20,
        sortType: this.filterOptions[this.currentFilter].type,
        page: this.page,
      })
        .then((res) => {
          this.productList = [...this.productList, ...res.list.data];
          if (this.page >= res.list.last_page) {
            this.hasMore = false;
          } else {
            this.hasMore = true;
          }
          this.isLoading = false;
        })
        .catch(() => {
          this.isLoading = false;
        });
    },

    loadSubCategoryProducts(subCategoryId) {
      // 这里可以添加请求二级分类商品的逻辑
      console.log(`Loading products for sub-category ID: ${subCategoryId}`);
    },
    setFilter(index) {
      this.currentFilter = index;
      this.init();
    },
    navigateToDetail(id) {
      uni.navigateTo({
        url: `/pages/shapping/detail?id=${id}`,
      });
    },
    openCart() {
      uni.navigateTo({
        url: "/pages/shapping/cart",
      });
    },

    navigateToHome() {
      uni.switchTab({
        url: "/pages/index/index",
      });
    },

    navigateToShop() {
      // 已在商城页面，不需要跳转
    },

    navigateToMine() {
      uni.switchTab({
        url: "/pages/mine/mine",
      });
    },

    showPointsRules() {
      this.showPointsModal = true;
    },

    hidePointsRules() {
      this.showPointsModal = false;
    },

    calculateMaxDiscount() {
      // 阶梯式积分抵扣计算逻辑
      const points = this.userPoints;
      let discountPercentage = 0;

      if (points >= 5000) {
        discountPercentage = 0.15; // 15%
      } else if (points >= 2000) {
        discountPercentage = 0.12; // 12%
      } else if (points >= 1000) {
        discountPercentage = 0.08; // 8%
      } else if (points >= 500) {
        discountPercentage = 0.05; // 5%
      }

      // 假设购物车总金额为300元，计算最大抵扣金额
      const cartTotal = 300;
      const pointsValue = points / 100; // 每100积分等值1元
      const maxByPoints =
        pointsValue > cartTotal * 0.5 ? cartTotal * 0.5 : pointsValue; // 最多抵扣50%
      const maxByPercentage = cartTotal * discountPercentage;

      // 取较小值作为最终抵扣金额
      const maxDiscount = Math.min(maxByPoints, maxByPercentage);

      return maxDiscount.toFixed(2);
    },
  },
};
</script>

<style lang="scss">
.iconfont {
  font-family: "iconfont" !important;
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
.shop-container {
  background-color: #f8f6f1; /* 米白色背景 */
  min-height: 100vh;
  // padding-bottom: 100rpx;
}

/* 搜索栏样式 */
.search-bar {
  padding: 20rpx 30rpx;
  background-color: #f8f6f1;
  position: sticky;
  top: 0;
  z-index: 10;
}

.search-input {
  background-color: #eeeae0;
  height: 70rpx;
  border-radius: 35rpx;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 10rpx;
}

.search-placeholder {
  color: #a89b88;
  font-size: 26rpx;
  font-family: "思源宋体", sans-serif;
}

/* 分类导航样式 */
.category-nav {
  display: flex;
  padding: 20rpx 0;
  background-color: #f8f6f1;
  white-space: nowrap;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);
}

.category-item {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 120rpx;
  margin: 0 20rpx;
}

.category-icon-wrapper {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  background-color: #eeeae0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10rpx;
}

.category-icon {
  width: 44rpx;
  height: 44rpx;
}

.category-name {
  font-size: 24rpx;
  color: #75695c;
  font-family: "思源宋体", sans-serif;
}

.category-item.active .category-icon-wrapper {
  background-color: #e2c675; /* 佛经黄 */
}

.category-item.active .category-name {
  color: #997a33;
  font-weight: bold;
}

/* 主推荐位样式 */
.featured-section {
  padding: 30rpx;
  margin-top: 20rpx;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.title-text {
  font-size: 32rpx;
  color: #4d3f33;
  font-family: "汉仪尚巍手书", "思源宋体", sans-serif;
  margin-right: 20rpx;
}

.title-decor {
  flex: 1;
  height: 2rpx;
  background: linear-gradient(to right, #997a33, rgba(153, 122, 51, 0.1));
}

.featured-scroll {
  white-space: nowrap;
}

.featured-item {
  display: inline-block;
  width: 300rpx;
  margin-right: 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
  background-color: #ffffff;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.featured-image {
  width: 300rpx;
  height: 300rpx;
}

.featured-info {
  padding: 16rpx;
}

.featured-name {
  font-size: 28rpx;
  color: #4d3f33;
  font-family: "思源宋体", sans-serif;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.featured-price {
  font-size: 32rpx;
  color: #8b5a2b; /* 檀木棕 */
  font-weight: bold;
  margin-top: 10rpx;
}

/* 商品列表样式 */
.product-section {
  padding: 30rpx;
}

.filter-bar {
  display: flex;
  margin: 20rpx 0 30rpx;
}

.filter-item {
  font-size: 28rpx;
  color: #75695c;
  margin-right: 40rpx;
  position: relative;
}

.filter-indicator {
  height: 6rpx;
  width: 0;
  background-color: #e2c675; /* 佛经黄 */
  position: absolute;
  bottom: -10rpx;
  left: 50%;
  transform: translateX(-50%);
  transition: width 0.3s;
}

.filter-item.active {
  color: #4d3f33;
  font-weight: bold;
}

.filter-item.active .filter-indicator {
  width: 100%;
}

.product-grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.product-item {
  width: 330rpx;
  margin-bottom: 30rpx;
  border-radius: 16rpx;
  overflow: hidden;
  background-color: #ffffff;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
}

.product-image {
  width: 330rpx;
  height: 330rpx;
}

.product-tag {
  position: absolute;
  top: 16rpx;
  right: 16rpx;
  background-color: #e2c675; /* 佛经黄 */
  color: #ffffff;
  font-size: 22rpx;
  padding: 6rpx 12rpx;
  border-radius: 6rpx;
}

.product-info {
  padding: 16rpx;
}

.product-name {
  font-size: 28rpx;
  color: #4d3f33;
  font-family: "思源宋体", sans-serif;
}

.product-desc {
  font-size: 24rpx;
  color: #a89b88;
  margin-top: 8rpx;
  height: 30rpx;
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.product-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16rpx;
}

.product-price {
  font-size: 32rpx;
  color: #8b5a2b; /* 檀木棕 */
  font-weight: bold;
}

.product-sold {
  font-size: 22rpx;
  color: #a89b88;
}

/* 加载更多样式 */
.load-more {
  text-align: center;
  padding: 30rpx 0;
}

.load-text {
  font-size: 28rpx;
  color: #a89b88;
  padding: 10rpx 40rpx;
  border-radius: 30rpx;
  background-color: #eeeae0;
  display: inline-block;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid #e2c675;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
  margin-right: 10rpx;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 二级分类样式 */
.subcategory-wrapper {
  background-color: #f8f6f1;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);
  padding: 10rpx 0;
}

.subcategory-nav {
  display: flex;
  white-space: nowrap;
  padding: 0 20rpx;
}

.subcategory-item {
  display: inline-block;
  padding: 10rpx 30rpx;
  margin: 0 10rpx;
  border-radius: 30rpx;
  background-color: #eeeae0;
}

.subcategory-name {
  font-size: 24rpx;
  color: #75695c;
  font-family: "思源宋体", sans-serif;
}

.subcategory-item.active {
  background-color: #e2c675; /* 佛经黄 */
}

.subcategory-item.active .subcategory-name {
  color: #ffffff;
  font-weight: bold;
}

/* 底部工具栏样式 */
.bottom-toolbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-around;
  border-top: 1rpx solid rgba(0, 0, 0, 0.05);
  z-index: 90;
}

.toolbar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 25%;
}

.toolbar-icon {
  width: 44rpx;
  height: 44rpx;
  margin-bottom: 6rpx;
}

.toolbar-icon-wrapper {
  position: relative;
}

.toolbar-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background-color: #e95f5c;
  color: #ffffff;
  font-size: 20rpx;
  min-width: 32rpx;
  height: 32rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 6rpx;
}

.toolbar-text {
  font-size: 22rpx;
  color: #75695c;
}

/* 积分抵扣提示样式 */
.points-tip {
  display: flex;
  align-items: center;
  padding: 16rpx 30rpx;
  background-color: #fff9e6;
  margin: 20rpx 30rpx;
  border-radius: 12rpx;
}

.points-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 10rpx;
}

.points-text {
  flex: 1;
  font-size: 24rpx;
  color: #997a33;
}

.points-detail {
  font-size: 24rpx;
  color: #78a77f;
  border-bottom: 1rpx solid #78a77f;
  padding-bottom: 2rpx;
}

/* 积分规则弹窗样式 */
.points-modal {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 200;
  display: flex;
  align-items: center;
  justify-content: center;
}

.points-modal-content {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  overflow: hidden;
}

.points-modal-header {
  position: relative;
  padding: 30rpx;
  text-align: center;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);
}

.points-modal-title {
  font-size: 32rpx;
  color: #4d3f33;
  font-family: "汉仪尚巍手书", "思源宋体", sans-serif;
}

.points-modal-close {
  position: absolute;
  top: 30rpx;
  right: 30rpx;
  font-size: 40rpx;
  color: #a89b88;
  line-height: 1;
}

.points-modal-body {
  padding: 30rpx;
  max-height: 800rpx;
  overflow-y: auto;
}

.points-rule-item {
  margin-bottom: 30rpx;
}

.points-rule-title {
  font-size: 28rpx;
  color: #4d3f33;
  font-weight: bold;
  margin-bottom: 16rpx;
}

.points-rule-desc {
  display: flex;
  flex-direction: column;
}

.points-rule-desc text {
  font-size: 26rpx;
  color: #75695c;
  line-height: 1.6;
}

.points-modal-footer {
  padding: 20rpx 30rpx 40rpx;
}

.points-modal-btn {
  background-color: #e2c675;
  color: #ffffff;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

/* 底部区域样式 */
.bottom-space {
  height: 120rpx;
}

/* 悬浮购物车样式 */
.float-cart {
  position: fixed;
  right: 40rpx;
  bottom: 120rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #78a77f; /* 青瓷绿 */
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
  z-index: 100;
}

.cart-icon {
  width: 50rpx;
  height: 50rpx;
}

.cart-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background-color: #e95f5c;
  color: #ffffff;
  font-size: 20rpx;
  min-width: 32rpx;
  height: 32rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 6rpx;
}
</style>
